<?php


namespace app\admin\controller;


use app\api\controller\Type;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Config;
use think\Controller;

class Api extends Controller
{

    //松鼠短视频官网;https://songshu.youyacao.com 该版本仅供个人使用 商用请联系官方购买正版授权
    public function upload()
    {

        if (Config::get("use_qiniu")) {
            return $this->upload_qiniu();
        }
        $type = input("type");
        $config = Config::get($type);
        if (!$config) {
            return error("上传类型错误");
        }

        $file = request()->file('file');
        if (!$file) {
            return error("请选择上传文件");
        }

        $info = $file->validate(['ext' => $config['ext']])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $type);

        if ($info) {
            $url = 'uploads/' . $type . "/" . str_replace(DS, "/", $info->getSaveName());
            if ($type == 'video') {
                $data = [
                    'url' => $url,
                    'img' => getImg($url)
                ];
                return success("上传成功", $data);
            } else {
                $data = [
                    'url' => $url
                ];
                return success("上传成功", $data);
            }


        } else {

            return error($file->getError());
        }
    }

    //松鼠短视频官网;https://songshu.youyacao.com 该版本仅供个人使用 商用请联系官方购买正版授权
    public function upload_qiniu()
    {
        if (request()->isPost()) {
            $file = request()->file('file');

            $filePath = $file->getRealPath();
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);

            $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
            require_once APP_PATH . '/../vendor/qiniu/autoload.php';

            $accessKey = Config::get('ACCESSKEY');
            $secretKey = Config::get('SECRETKEY');

            $auth = new Auth($accessKey, $secretKey);
            $bucket = Config::get('BUCKET');
            $domain = Config::get('DOMAIN');
            $token = $auth->uploadToken($bucket);

            $uploadMgr = new UploadManager();

            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return error($err);
            } else {

                return success("上传成功", "http://" . $domain . "/" . $ret['key']);
            }
        }
    }
}